    /*
 * Copyright (c) 2022, yifengling0. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. No personal names or organizations' names associated with the
 *    Atomthreads project may be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE ATOMTHREADS PROJECT AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include "atom.h"
#define ATOM_NONE_STANDARDIO
#include "drv_pwm.h"
#include "mraa/pwm.h"


typedef struct pwm_channel {
    int channel;
    mraa_pwm_context context;
}pwm_channels;

static pwm_channels pwm_list[] = {
    {0, NULL}, {1, NULL}
};

#define ITEM_NUM(items) sizeof(items) / sizeof(items[0])
static int pwm_ioctl(FD fd, int function, void* arg)
{
	int ret = OK;

	switch (function) {
	case IOCTL_PWM_SET:
	{
		PwmIoctlSet* set = (PwmIoctlSet*)arg;
		if (set->channel < ITEM_NUM(pwm_list)) {
			mraa_pwm_period_us(pwm_list[set->channel].context, set->period);
			mraa_pwm_write(pwm_list[set->channel].context, (float)set->pulse / (float)set->period);
		}
		else {
			ret = NG;
		}
	}
		break;
	case IOCTL_PWM_ENABLE:
	case IOCTL_PWM_DISABLE:
	{
		PwmIoctlState* state = (PwmIoctlState*)arg;
		if (state->channel < ITEM_NUM(pwm_list)) {
			mraa_pwm_enable(pwm_list[state->channel].context, state->enable);
		}
		else {
			ret = NG;
		}
	}
	break;
	}

    return ret;
}

static void pwm_init(UpboardPwm* pwm)
{
    for (int i = 0; i < ITEM_NUM(pwm_list); i++) {
        pwm_list[i].context = mraa_pwm_init(pwm_list[i].channel);
    }
}

void UpPwmCreate(UpboardPwm*pwm)
{
    PwmCreate(&pwm->super, pwm_ioctl);
    pwm_init(pwm);
}
